//
//  ComposeViewController.swift
//  glzbowei
//
//  Created by 高伦展 on 2018/2/23.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

// MARK: - 撰写控制器
class ComposeViewController: UIViewController {

    /// 照片选择控制器
    private lazy var picturePickerController = PicturePickerController()
    
    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(em: emoticon)
    }
    
    // MARK: - 监听方法
    // 关闭
    @objc private func close(){
        // 关闭键盘
        textView.resignFirstResponder()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc func sendStatus(){
        
        let text = textView.emoticonText
        let image = picturePickerController.pictures.last //UIImage(named: "new_feature_1")
        NetworkTools.sharedTools.sendStatus(status: text,image: image) { (result, error) in
           
            SVProgressHUD.show()
            
            if error != nil{
                print("出错了")
                SVProgressHUD.showInfo(withStatus: "您的网络不给力")
                return
            }
            
            SVProgressHUD.dismiss()
            print(result ?? AnyObject.self)
            
            self.close()
        }
    }
    
    @objc private func selectPicture(){
        
        //退掉键盘
        textView.resignFirstResponder()
        //判断是否
        if picturePickerController.view.frame.height > 0{
            return
        }
        
        picturePickerController.view.snp.updateConstraints { (make) in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        //重建约束 - 灰浆之前的所有约束删除
        textView.snp.remakeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaInsets.top)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.bottom.equalTo(picturePickerController.view.snp.top)
        }
        
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
        }
        
    }
    
    /// 选择表情键盘
    @objc private func selectEmoticon(){
        // 1. 退掉键盘
        textView.resignFirstResponder()
        // 2. 设置键盘
        textView.inputView = textView.inputView == nil ?emoticonView:nil
        // 3. 重新激活键盘
        textView.becomeFirstResponder()
    }
    
    // MARK: - 键盘处理
    /// 键盘变化处理
    @objc private func keyboardChanged(n:Notification){
        // 获取目标的动画时长 - 字典中的数值是 NSNumber
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 获取目标的 rect - 字典中的`结构体`是 NSValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        // 动画曲线数值
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue
        
        let offset = -view.bounds.height + rect.origin.y
        
        toolbar.snp.updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp.bottom).offset(offset)
        }
        
        // 动画 － UIView 块动画 本质上是对 CAAnimation 的包装
        UIView.animate(withDuration: duration) {
            // 设置动画曲线
            /**
             曲线值 = 7
             － 如果之前的动画没有完成，有启动了其他的动画，让动画的图层直接运动到后续动画的目标位置
             － 一旦设置了 `7`，动画时长无效，动画时长统一变成 0.5s
             */
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
        // 调试动画时长 － keyPath 将动画添加到图层
        //let anim = toolbar.layer.animation(forKey: "position")
    }
    
    override func loadView() {
        view = UIView()
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册键盘通知
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(ComposeViewController.keyboardChanged(n:)),
                                               name: NSNotification.Name.UIKeyboardWillChangeFrame,
                                               object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerController.view.frame.height == 0{
            textView.becomeFirstResponder()
        }
        
    }
    
    //工具条
    private lazy var toolbar = UIToolbar()
    //文本视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
        
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        //始终允许垂直滚动
        tv.alwaysBounceVertical = true
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        
        tv.delegate = self
        
        return tv
    }()
    
    //占位标签
    private lazy var placeHolderLabel : UILabel = UILabel(title: "分享新鲜事...", fontSize: 18, color: UIColor.lightGray)
    
}

extension ComposeViewController:UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        placeHolderLabel.isHidden = textView.hasText
    }
}

private extension ComposeViewController{
    
    func setupUI() {
        //取消自动调整滚动视图间距
        //automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.white
        
        prepareNavigationBar()
        prepareToolbar()
        prepareTextView()
        preparePicturePicker()
    }
    
    private func preparePicturePicker(){
        
        //添加子控制器
        addChildViewController(picturePickerController)
        //添加视图
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        //view.addSubview(picturePickerController.view)
        //自动布局
        picturePickerController.view.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom)
            make.right.equalTo(view.snp.right)
            make.left.equalTo(view.snp.left)
            //make.height.equalTo(view.snp.height).multipliedBy(0.6)
            make.height.equalTo(0)
        }
    }
    
    private func prepareTextView(){
        view.addSubview(textView)
        
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaInsets.top)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.bottom.equalTo(toolbar.snp.top)
        }
        
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.top).offset(8)
            make.left.equalTo(textView.snp.left).offset(5)
        }
    }
    
    private func prepareToolbar(){
        view.addSubview(toolbar)
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        toolbar.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.height.equalTo(44)
        }
        
        // 添加工具栏按钮
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticon"],
                            ["imageName": "compose_addbutton_background"]]

        var items = [UIBarButtonItem]()
        
        for dict in itemSettings{
            //let image = UIImage(named: dict["imageName"]!)
            
            //let item = UIBarButtonItem(image: image, style: .plain, target: nil, action: nil)
            
//            let button  = UIButton(imgName: dict["imageName"]!, bgImgName: nil)
//
//            if let actionName = dict["actionName"]{
//                button.addTarget(self, action: Selector(actionName), for: .touchUpInside)
//            }
//
//            let item = UIBarButtonItem(customView: button)
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolbar.items = items
    }
    
    //设置导航栏
    private func prepareNavigationBar() {
     
        //左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(ComposeViewController.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(ComposeViewController.sendStatus))
        
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGray)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(titleView.snp.centerX)
            make.bottom.equalTo(titleView.snp.bottom)
        }
        
        nameLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(titleView.snp.centerX)
            make.top.equalTo(titleView.snp.top)
        }
    }
}
